var util = require('util.js')
var md5Util = require('md5.js')
var bibleData = require('bible.js')
var config = require('config.js')

function getLastRead(i){
  return wx.getStorageSync('lsr' + i);
}

function setLastRead(val){
  var index = 24;
  var nn=0;
  for (var i = 0; i < 25; i++) {
      var v = wx.getStorageSync('lsr' + i);
      if (v == val) {
         index=i;
         break;
      }
    if (v == '0' && index==24){
        index=i;
      }
  }
    for (var i = index; i > 0; i--) {
      var k = i - 1;
      var pre = wx.getStorageSync('lsr' + k);
      wx.setStorageSync("lsr" + i, pre);
    }

  wx.setStorageSync("lsr0", val);
}




function getBookName(key) {
  var info = wx.getStorageInfoSync();
  if (!util.contains(info.keys, "bkn" + key)) {
    var oldBook = bibleData.oldbooks;
    var newBook = bibleData.newbooks;
    for (var i = 0; i < oldBook.length; i++) {
      wx.setStorageSync('bkn' + oldBook[i].bookId, oldBook[i].bookName);
    }
    for (var i = 0; i < newBook.length; i++) {
      wx.setStorageSync('bkn' + newBook[i].bookId, newBook[i].bookName);
    }
  }
  return wx.getStorageSync('bkn' + key);
}

function transArrData(verseArr, selContents, selIndexs, selChapters) {
  var that = this;
  var chapterArr = new Array();
  for (var i = 0; i < verseArr.length; i++) {
    var id = verseArr[i].bookId + "-" + verseArr[i].chapterId;
    if (chapterArr.indexOf(id) == -1) {
      var verIndexArr = new Array();
      var verContentArr = new Array();
      chapterArr.push(id);
      for (var j = 0; j < verseArr.length; j++) {
        var id1 = verseArr[j].bookId + "-" + verseArr[j].chapterId;
        if (id1 == id) {
          verIndexArr.push(verseArr[j].verseId);
          verContentArr.push(verseArr[j].content)

        }
      }
      var bookId = parseInt(verseArr[i].bookId);
      var chapterId = verseArr[i].chapterId;
      var bookName = getBookName(bookId);
      var selIndexs0 = new Array();
      var selChapters0 = new Array();
      var selContents0 = new Array();
      getSelVerses(bookName, bookId, chapterId, verIndexArr, verContentArr, selContents0, selIndexs0, selChapters0)
      for (var kk = 0; kk < selIndexs0.length; kk++) {
        selContents.push(selContents0[kk]);
        selIndexs.push(selIndexs0[kk]);
        selChapters.push(selChapters0[kk]);
      }
    }
  }
}

function getSelVerses(bookName, bookId, chapterId, verIndexArr, verContentArr, selContents, selIndexs, selChapters) {
  var minx = -1;
  var maxx = -1;
  var maxmin = new Array();
  var nn = 0;
  var index = verIndexArr.length;
  for (var i = 0; i < index; i++) {
    if (minx == -1) {
      minx = verIndexArr[i];
      maxx = verIndexArr[i];
    }
    if (i + 1 < index) {
      if (verIndexArr[i + 1] - verIndexArr[i] == 1) {
        maxx = verIndexArr[i + 1];
      } else {
        maxmin[nn] = new Array();
        maxmin[nn][0] = minx;
        maxmin[nn][1] = maxx;
        nn = nn + 1;
        minx = -1;
        maxx = -1;
      }
    } else {
      maxmin[nn] = new Array();
      maxmin[nn][0] = minx;
      maxmin[nn][1] = maxx;
    }
  }
  var bname = bookName;
  var bid = bookId;
  var cid = chapterId;
  var kn = 0;
  var selN = 0;
  for (var k = 0; k <= nn; k++) {
    var ma = maxmin[k][0];
    var mb = maxmin[k][1];
    if (ma == mb) {
      selChapters[selN] = bid + "|" + cid + ":" + ma;
      selContents[selN] = verContentArr[kn];
      selIndexs[selN] = bname + cid + ":" + ma;
      selN = selN + 1
      kn = kn + 1;
    } else {
      var ln = mb - ma + 1;
      var cnten = "";
      for (var kd = 0; kd < ln; kd++) {
        cnten = cnten + verContentArr[kn + kd];
      }
      kn = kn + ln;
      selChapters[selN] = selChapters[selN] = bid + "|" + cid + ":" + ma + "-" + mb;
      selContents[selN] = cnten;
      selIndexs[selN] = bname + cid + ":" + ma + "-" + mb;
      selN = selN + 1;
    }
  }
}

function punchCalcLastYear(punch) {
  var bibeReadArr = new Array();
  for (var i = 0; i < 66; i++) {
    bibeReadArr[i] = new Array();
    bibeReadArr[i][0] = 0; //在读，没读完一次的状态
    if (i < 39) {
      var chapterCount = bibleData.oldbooks[i].chapterCount;
      for (var j = 1; j <= chapterCount; j++) {
        bibeReadArr[i][j] = 0;
      }
    } else {
      var chapterCount = bibleData.newbooks[i - 39].chapterCount;
      for (var j = 1; j <= chapterCount; j++) {
        bibeReadArr[i][j] = 0;
      }
    }
  }
  //当前年月日
  var arr1 = punch.replace(/#/g, "").split(';').slice(1);
  var currDate = new Date();
 
  currDate.setFullYear(currDate.getFullYear() - 1);
  for (var i = 0; i < arr1.length; i++) {
    var c0 = arr1[i];
    if (c0 != "") {
      c0 = c0.replace(/#/g, "");
      var arr2 = c0.split("-");
      var c1 = arr2[0] + "/" + arr2[1] + "/" + arr2[2];
      var c11 = new Date(c1);
      var bibleId = parseInt(arr2[3]);
      var chapterId = parseInt(arr2[4]);
      if (c11 > currDate) {
        try {
          bibeReadArr[bibleId - 1][chapterId] = bibeReadArr[bibleId - 1][chapterId] + 1;
        }
        catch (err) {
           bibleId=bookId+0;
          chapterId = chapterId+0;
        }
       
      }
    }
  }
  for (var i = 0; i < 66; i++) {
    var min = 100;
    var max = 0;
    for (var j = 1; j < bibeReadArr[i].length; j++) {
      if (min > bibeReadArr[i][j]) {
        min = bibeReadArr[i][j];
      }
      if (max < bibeReadArr[i][j]) {
        max = bibeReadArr[i][j];
      }
    }
    bibeReadArr[i][0] = min;
    if (max == 0) { //一次都没读的状态
      bibeReadArr[i][0] = -1;
    }
  }
  return bibeReadArr;
}

function punchCalc2(a, b) {
  var c = parseInt(a * 5 / b)
  if (c == 1) {
    return [0, 1, 1, 1, 1];
  } else if (c == 2) {
    return [0, 0, 1, 1, 1];
  } else if (c == 3) {
    return [0, 0, 0, 1, 1];
  } else if (c == 4) {
    return [0, 0, 0, 0, 1];
  } else if (c == 5) {
    return [0, 0, 0, 0, 0];
  }
  return [1, 1, 1, 1, 1];
}


function encryptToken(timestamp, nonce) {
  var token = "weixin2018";
  var arrstr = nonce + token + timestamp + nonce;
  //md5加密
  var signature = md5Util.hexMD5(arrstr);

  return signature;

}

function randomWord(randomFlag, min, max) {
  var str = "";
  var range = min;
  var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min;
  }
  for (var i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}

function punchCalc1(punch) {
  var result = {
    todaycount: 0,
    moncount: 0,
    yearcount: 0,
    allcount: 0
  };
  var todaycount = 0;
  var moncount = 0;
  var yearcount = 0;
  var allcount = 0;
  var arr1 = punch.replace(/#/g, "").split(';').slice(1);
  var currDate = util.getNowShortFormatDate();
  var currMon = currDate.substr(0, 7);
  var currYear = currDate.substr(0, 4);
  var todayVal = "";
  for (var i = 0; i < arr1.length; i++) {
    var c0 = arr1[i];
    if (c0 != "") {
      allcount = allcount + 1;
      c0 = c0.replace(/#/g, "");
      var arr2 = c0.split("-");
      var c1 = arr2[0] + "-" + arr2[1] + "-" + arr2[2];
      var c2 = arr2[0] + "-" + arr2[1];
      var c3 = arr2[0];
      var chapter = "#" + arr2[3] + "-" + arr2[4] + "#";
      if (c1 == currDate) {
        todaycount = todaycount + 1;
        if (todayVal == "") {
          todayVal = chapter;
        } else {
          todayVal = todayVal + ";" + chapter;
        }
      }
      if (c2 == currMon) {
        moncount = moncount + 1;
      }
      if (c3 == currYear) {
        yearcount = yearcount + 1;
      }
    }
  }
  result.todaycount = todaycount;
  result.moncount = moncount;
  result.yearcount = yearcount;
  result.allcount = allcount;
  result.todayval = todayVal;
  return result;
}


function wifiUpdateBibleData(cb) {
  
  var that = this;
  var storageing = 0;
  var info = wx.getStorageInfoSync();
  if (!util.contains(info.keys, "storageing")) {
    wx.setStorageSync('storageing', '1'); //设置正在缓存中
  } else {
    storageing = wx.getStorageSync("storageing");
    if (storageing == '1') {
      typeof cb == "function" && cb();
      return;
    } else {
      wx.setStorageSync('storageing', '1'); //设置正在缓存中
    }
  }
  wx.request({
    url: that.https + '/conf/getval?mkey=version',
    method: 'GET',
    success: function(res0) {
      var ver0 = res0.data;
      var version = wx.getStorageSync('version')
      if (version != ver0) { //判断本地缓存版本和服务器是否一致，不一致则缓存
        wx.request({
          url: that.https + '/chapter/list_all',
          method: 'GET',
          success: function(res2) {
            var bibeData = res2.data;
            for (var k = 0; k < 66; k++) {
              wx.setStorage({ //添加缓存
                key: "bk" + (k + 1),
                data: bibeData[k]
              });
            }
            wx.setStorageSync('version', ver0);
            wx.setStorageSync('storageing', '0'); //设置缓存结束
            typeof cb == "function" && cb();
            setTimeout(function(){
              wx.hideLoading();
            },1000);
            
          }
        })
      } else {
        wx.setStorageSync('storageing', '0'); //设置缓存结束
        typeof cb == "function" && cb();
        wx.hideLoading();
      }
    },
    fail: function(res1) {
      wx.setStorageSync('storageing', '0'); //设置缓存结束
    }
  });
}

function getRightChapter(bookId, chapterId, chapterCount) {
  bookId = parseInt(bookId);
  chapterId = parseInt(chapterId);
  chapterCount = parseInt(chapterCount);
  var oldbook = bibleData.oldbooks;
  var newbook = bibleData.newbooks;
  var chapter = {};
  if (chapterId < chapterCount) {
    chapter.bookId = bookId;
    chapter.chapterId = chapterId + 1;
    chapter.chapterCount = chapterCount;
    chapter.bookName = getBookName(bookId);
  } else {
    chapter.chapterId = 1;
    if (bookId < 66) {
      bookId = bookId + 1;
      chapter.bookId = bookId;
    } else {
      chapter.bookId = 1;
      bookId = 1;
    }
    if (bookId > 39) {
      chapter.bookName = newbook[bookId - 40].bookName;
      chapter.chapterCount = newbook[bookId - 40].chapterCount;
    } else {
      chapter.bookName = oldbook[bookId - 1].bookName
      chapter.chapterCount = oldbook[bookId - 1].chapterCount;
    }
  }
  chapter.content = getBibleContent(chapter.bookId, chapter.chapterId);
  return chapter;
}

function getLeftChapter(bookId, chapterId, chapterCount) {
  var oldbook = bibleData.oldbooks;
  var newbook = bibleData.newbooks;
  bookId = parseInt(bookId);
  chapterId = parseInt(chapterId);
  chapterCount = parseInt(chapterCount);
  var chapter = {};
  if (chapterId > 1) {
    chapter.chapterId = chapterId - 1;
    chapter.bookId = bookId;
    chapter.chapterCount = chapterCount;
    chapter.bookName = getBookName(bookId);
  } else {
    chapter.chapterId = 1;
    if (bookId > 1) {
      bookId = bookId - 1;
      chapter.bookId = bookId;
    } else {
      chapter.bookId = 66;
      bookId = 66;
    }
    if (bookId > 39) {
      chapter.bookName = newbook[bookId - 40].bookName;
      chapter.chapterCount = newbook[bookId - 40].chapterCount;
    } else {
      chapter.bookName = oldbook[bookId - 1].bookName
      chapter.chapterCount = oldbook[bookId - 1].chapterCount;
    }
    chapter.chapterId = chapter.chapterCount;
  }
  chapter.content = getBibleContent(chapter.bookId, chapter.chapterId);
  return chapter;
}

function getBibleContent(bookId, chapterId) {
  var content = "";
  var key = "bk" + bookId;
  var bookData = wx.getStorageSync(key);
  for (var i = 0; i < bookData.length; i++) {
    if (chapterId == bookData[i].chapterId) {
      content = bookData[i].content;
      //   console.log("缓存读取" + bookName + "第" + chapterId + "章");
      break;
    }
  }

  return content;
}

function validBible() {
  return bibleData.validBible();
}

function reLoadBible(){
  return bibleData.reLoadBible();
}

function checkDate(){
  return bibleData.checkDate()
}

//获取前len条未重复记录
function getTopNRead(len,bookId,chapterId){
  var ppp = [];
  var ii = 0;
  for (var i = 0; i < 25; i++) {
    var v = getLastRead(i);
    if (v.length > 6) {
      var arr000 = v.split('-');
      var time1 = arr000[0] + '-' + arr000[1] + '-' + arr000[2];
      var bookId1 = arr000[3];
      var chapterId1 = arr000[4];
      var bookName1="";
      var bookAddName1="";
      if (bookId1 > 39) {
        bookName1 = bibleData.newbooks[bookId1 - 40].bookName;
        bookAddName1 = bibleData.newbooks[bookId1 - 40].bookAddName;
      } else {
        bookName1 = bibleData.oldbooks[bookId1 - 1].bookName
        bookAddName1 = bibleData.oldbooks[bookId1 - 1].bookAddName;
      }
      var text1 = bookAddName1+ ':' + arr000[4];
      var newV = { bookId: bookId1, chapterId: chapterId1,text:text1,bookName:bookName1};
      if (ppp.indexOf(newV)<0){
        if(bookId!=bookId1||chapterId!=chapterId1){
          ppp.push(newV);
          ii = ii + 1
        }
      }
      if (ii === len) {
        break;
      }
    }
   
  }
  return ppp;
 // var punchArr01 = ppp;//[];// punch.replace(/#/g, "").split(';').slice(1);

}
                  
var https = config.https;//'https://ssl.zhi22.cn';
var cdnurl = config.cdnurl;//'https://cdn.zhuneiyun.cn/biblemini/audios/';
//var https = 'http://localhost:8123/BibleWebservice';

//var https = 'http://moses.iok.la/BibleWebservice';


var enablev=bibleData.enablev;
//var fbtime = '08/10/2018 18:00:00'; //改=======现在是通过修改 数据库confdics表下的enablev值实现，0或1，管理员通过后台管理可以直接即时切换小程序主界面
var pageEnable = validBible(); //

module.exports = {
  getBookName: getBookName,
  transArrData: transArrData,
  wifiUpdateBibleData: wifiUpdateBibleData,
  punchCalc1: punchCalc1,
  punchCalc2: punchCalc2,
  encryptToken: encryptToken,
  randomWord: randomWord,
  punchCalcLastYear: punchCalcLastYear,
  getBibleContent: getBibleContent,
  getRightChapter: getRightChapter,
  getLeftChapter: getLeftChapter,
  https: https,
  getLastRead: getLastRead,
  setLastRead: setLastRead,
  validBible: validBible,
  reLoadBible: reLoadBible,
  pageEnable: pageEnable,
  enablev: enablev,
  cdnurl:cdnurl,
  getTopNRead: getTopNRead,
  checkDate: checkDate
}